<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>URL.createObjectURL 图片视频上传 预览格式为Blob </title>
  <style type="text/css">
    .imgshow {
      padding: 2px;
      border: 2px antiquewhite;
      transition: background 1s;
      -moz-transition: background 1s;
      -webkit-transition: background 1s;
      -o-transition: background 1s;
    }

    .imgshow:hover {
      background: rgba(0, 0, 0, 0.2);
    }

    input[type=file] {
      top: 0;
      left: 0;
      width: 100px;
      height: 100px;
      overflow: hidden;
      /* cursor: pointer; */
      /*设置input不显示*/
      /* opacity: 0; */
      background: url(../img/24.png) round;
      cursor: pointer;
      /* 上面的代码是常规设置， 即：引入一个图片背景，设置在中心位置，大小和按钮的大小一致，以及鼠标指针为手型 */
      /*设置背景图片大小*/
      background-size: 100%;
      display: block;
      font-size: 0;
      line-height: 0;
      text-indent: -9999px;
    }

    input[type=file]:active {
      border: white;
    }

    .imgcontshow {
      visibility: hidden;
      opacity: 0;
      transform: scaleY(0);
      transition: .3s;
      animation: show .5s forwards;
    }

    @keyframes show {
      0% {
        visibility: visible;
        opacity: 1;
        transform: scaleY(0)
      }

      40% {
        visibility: visible;
        opacity: 1;
        transform: scaleY(1)
      }

      60% {
        visibility: visible;
        opacity: 1;
        transform: scaleY(0)
      }

      80% {
        visibility: visible;
        opacity: 1;
        transform: scaleY(2)
      }

      100% {
        visibility: visible;
        opacity: 1;
        transform: scaleY(1)
      }
    }

    @keyframes fadenum {

      /*设置内容由显示变为隐藏*/
      0% {
        opacity: 0;
      }

      100% {
        opacity: 1;
      }
    }
  </style>
</head>

<body>
  <input type="file" multiple="multiple" maxsize="2" accept="application/application/vnd.android.package-archive" />
  <div id="vessel"></div>

  <img src="" id="imgbole" />
</body>
<script src="../js/inCommonUse.js" type="text/javascript" charset="utf-8"></script>


<script type="text/javascript">
  // Ajax('post','http://60.10.165.110:8001/fbjd/msg/weather',{city:101090608})
  // console.log(new FindDom().getSelector('[type=file]'))

  const imgs = document.querySelector('input[type=file]'),//获取file
    vessel = document.getElementById('vessel'),
    filetype = imgs.getAttribute('datatype'); //获取自定义读取图片类型

  let imgsBlobArry = [], //存放blob数据
    imgArrylist = [], //存放图片对象
    Eedom = [],
    fileTypes = ['image', 'video', 'audio'];//常见文件上传类型数组
  imgs.onchange = function update()
  {

    const typeFile = imgs.accept || imgs.accept.replace(/\s/g, "").split(",");

    for (let i = 0; i < imgs.files.length; i++) { //获取的图片放入数组
      // console.log(imgs.files[i].type);
      if (parseInt(imgs.getAttribute("maxsize")) - 1 < i) {
        throw Error('超出了数量', 'Exceeded number of custom files')
        break;
      }

      // if (typeFile.indexOf(imgs.files[i].type) ===-1) { console.warn('上传文件类型有误'); continue; }

      let blobs = window.URL.createObjectURL(imgs.files[i]) //获取blob二进制数据，可用来显示
      imgArrylist.push(imgs.files[i]);
      imgsBlobArry.push({
        name: imgs.files[i].name,
        fileType: imgs.files[i].type,
        size: conver(imgs.files[i].size),
        uer: blobs,
        lastModifiedDate: imgs.files[i].lastModifiedDate
      });

      let TheLabel;
      console.log(imgs.files[i].type);
      fileTypes.includes();
      if (String(imgs.files[i].type).includes('image')) {
        TheLabel = new Image;

      } else if (String(imgs.files[i].type).includes('video')) {
        TheLabel = document.createElement('video');

      } else if (String(imgs.files[i].type).includes('audio')) {
        TheLabel = new Audio;

      } else { //其他文件
        TheLabel = document.createElement('div');
      }

      let imgCont = document.createElement('div'); //最外层div
      let close = document.createElement('p'); //最外层div
      let progress = document.createElement('div'); // 显示进度条div
      close.className = 'close';
      close.style = `text-align: end;line-height: 0;cursor: pointer;`;
      close.innerHTML = `X`;

      TheLabel.style = `width:100%;height:100%`;
      TheLabel.src = blobs;
      TheLabel.id = "examine";
      imgCont.className = "imgshow imgcontshow";
      imgCont.style = `width: 10%;height: 10%;float: left;`;
      progress.style = `width:100%;height:0.2rem;background:#10affb`;

      if (progress.tagName === 'DIV') {
        TheLabel.innerHTML = `<img src="../img/file.jpg" alt="文件" style="width: 100%;">`
      }
      imgCont.appendChild(close);
      imgCont.appendChild(TheLabel);
      imgCont.appendChild(progress);
      vessel.appendChild(imgCont);

      Eedom.push(TheLabel)
      // shouimg.src = blobs
      // postJSON('http://localhost:3692/imgeblob',{city:imgsBlobArry}).then()
      // postJSON('http://localhost:3692/imgeblob',{city:blobs}).then()		


      // reduceImg(DOM)
    }

    // window.URL.revokeObjectURL(blobs) //手动回收


    if (imgsBlobArry.length > parseInt(imgs.getAttribute("maxsize"))) {
      console.log("超出数量")
      imgs.style.display = 'none';

    } else {
      imgs.style.display = "table";
    }

    Eedom.forEach((e, index) =>
    { //图片压缩
      reduceImg({
        src: e.src,
        index
      })
    })

    //图片压缩方法
    function reduceImg(data)
    {
      const {
        src,
        index,
        w = 200,
        h = 200,
        type = 'blob'
      } = data;
      let img = new Image();
      img.src = src
      setTimeout(() =>
      {
        //图片的原始尺寸
        let originWidth = img.width;
        let originHeight = img.height;
        //最大尺度的尺寸限制默认在 200*200
        let maxWidth = w,
          maxHeight = h;
        //目标尺寸
        console.log(originWidth, originHeight)
        let targetWidth = originWidth,
          targetHeight = originHeight;
        if (originWidth > maxWidth || originHeight > maxHeight) { //如果原始尺寸大于了设定的最大尺寸
          if (originWidth / originHeight > maxWidth / maxHeight) { //图片原本的宽高比例大于了设定的宽高比例
            //大于规定的比例 证明 原始宽度大于高度 -》所以按照高度除以宽度的比例去缩放高度
            targetWidth = maxWidth;
            targetHeight = Math.round(maxWidth * (originHeight / originWidth));
          } else {
            //小于则表明 原始高度大于原始宽度 -》所以按照宽度除以高度的比例去缩放宽度
            targetHeight = maxHeight;
            targetWidth = Math.round(maxHeight * (originWidth / originHeight));
          }
        }
        let canvas = document.createElement('canvas');
        let context = canvas.getContext('2d');
        // canvas对图片进行缩放
        canvas.width = targetWidth;
        canvas.height = targetHeight;
        // 清除画布
        context.clearRect(0, 0, targetWidth, targetHeight);
        // 图片压缩

        let imgys = document.createElement('img');

        imgys.src = src;
        context.drawImage(imgys, 0, 0, targetWidth, targetHeight);
        // canvas转为blob并上传
        if (type === 'blob') {
          canvas.toBlob(function (blob)
          {

            imgsBlobArry[index].uer = window.URL.createObjectURL(blob)

          }, 'image/png', 0.95);
        } else {
          imgsBlobArry[index].uer = canvas.toDataURL('image/png')
        }

      }, 100)

    }

    console.log(imgsBlobArry)

    function conver(limit)
    { //图片大小 mb 换算
      let size = "";
      if (limit < 0.1 * 1024) { //如果小于0.1KB转化成B
        size = limit.toFixed(2) + "B";
      } else if (limit < 0.1 * 1024 * 1024) { //如果小于0.1MB转化成KB
        size = (limit / 1024).toFixed(2) + "KB";
      } else if (limit < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
        size = (limit / (1024 * 1024)).toFixed(2) + "MB";
      } else { //其他转化成GB
        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
      }
      let sizestr = size + "";
      let len = sizestr.indexOf("\.");
      let dec = sizestr.substr(len + 1, 2);
      if (dec === "00") { //当小数点后为00时 去掉小数部分
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
      }
      return sizestr;
    }
  }


  //点击图片查看
  let el = window.document.body; //声明一个变量，默认值为body
  window.document.body.onclick = function (event)
  {
    if (event.target.id === "") {
      if (event.target.id === 'showimg' || event.target.parentNode.id === 'showimg') {
        document.body.removeChild(document.getElementById('showimg'))
      }
    }
    let lookOver = document.getElementById('imgShow');
    if (event.target.tagName === 'IMG' || event.target.tagName === 'VIDEO' || event.target.tagName === 'Audio') {

      let showimg = event.target.tagName === "IMG" ? new Image : event.target.tagName === "VIDEO" ? document.createElement(
        'video') : new Audio;
      showimg.autoplay = true
      showimg.controls = true
      let divshow = document.createElement('div');
      showimg.style =
        `position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);animation: fadenum 2s forwards`;
      showimg.src = event.target.src;
      divshow.id = 'showimg';
      divshow.style = `position: fixed;top: 0px;width: 100%;height: 100%;background: rgba(0,0,0,0.1);text-align:center;`

      divshow.appendChild(showimg)

      if (!lookOver) {
        document.body.appendChild(divshow)
      }

    }

    if (event.target.id === 'showimg' || event.target.parentNode.id === 'showimg') {
      document.body.removeChild(document.getElementById('showimg'))
    }
    if (event.target.tagName === 'P') {
      document.querySelectorAll('.close').forEach((tiem, index) =>
      {
        tiem.onclick = function ()
        {
          console.log(this.parentNode);
          document.getElementById('vessel').removeChild(this.parentNode);
          imgsBlobArry.splice(index, 1);
        }
      });
      if (imgsBlobArry.length > parseInt(imgs.getAttribute("maxsize"))) {
        console.log("超出数量")
        imgs.style.display = 'none';

      } else {
        imgs.style.display = "table";
      }
    }
  };



  function postJSON(url, data)
  {
    return new Promise((resolve, reject) =>
    {
      let xhr = new XMLHttpRequest()
      xhr.open("POST", url, true)
      xhr.datatype = 'json'
      xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");

      xhr.onreadystatechange = function ()
      {
        if (this.readyState === 4) {
          if (this.status === 200) {
            resolve(JSON.parse(this.responseText), this)
          } else {
            let resJson = {
              code: this.status,
              response: this.response
            }
            reject(resJson, this)
          }
        }
      }

      xhr.send(JSON.stringify(data))
    })
  }
</script>

</html>